package ru.sanluck.tg.command;

import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.bots.AbsSender;
import ru.sanluck.books.Book;
import ru.sanluck.books.BookSearchService;
import ru.sanluck.tg.Dialog;
import ru.sanluck.tg.TgUserService;
import ru.sanluck.tg.UserMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class Search extends AbsTgCommand {

    private static final String SEARCH = "/search";
    private static final String NOTHING_FOUND = "По вашему запросу : \"%s\" ничего не нашли";
    private static final String FOUND_BOOKS = "Нашли книги : \n %s";
    private static final String FOUND_SINGLE_BOOK = "Найдена книга : %s";

    private final BookSearchService bookSearchService;

    public Search(TgUserService tgUserService, UserMapper userMapper, BookSearchService bookSearchService) {
        super(tgUserService, userMapper);
        this.bookSearchService = bookSearchService;
    }

    @Override
    public String commandText() {
        return SEARCH;
    }

    @Override
    public Set<Dialog> dialogs() {
        return Set.of(Dialog.SEARCH);
    }

    @Override
    public void executeCommand(Message message, AbsSender sender) {
        List<Book> books = new ArrayList<>();

        if (message.isUserMessage() && !message.isCommand()) {
            String searchText = message.getText();
            books.addAll(bookSearchService.searchBooks(searchText));

            if (books.isEmpty()) {
                sendTextMessage(message.getChatId(), NOTHING_FOUND.formatted(searchText), sender);
                return;
            }

            sendFoundedBooksMessage(books, message, sender);
        }
    }

    private void sendFoundedBooksMessage(List<Book> books, Message message, AbsSender sender) {
        if (books.size() == 1) {
            sendTextMessage(message.getChatId(), FOUND_SINGLE_BOOK.formatted(getBooksText(books)), sender);
        } else {
            sendTextMessage(message.getChatId(), FOUND_BOOKS.formatted(getBooksText(books)), sender);
        }
    }

    private String getBooksText(List<Book> books) {
        return books.stream()
                .map(this::bookText)
                .collect(Collectors.joining("\n"));
    }

    private String bookText(Book book) {
        return "Книга - ИД: " + book.getId()
                + ", автор: " + book.getAuthor()
                + ", название: " + book.getName();
    }
}
